package com.lagou.edu.util;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class MailUtils {
    //自己发给自己
    private String host = ""; // smtp服务器
    private String protocol = "";
    private String from = ""; // 发件人地址
    private String fromPassword = ""; // 授权码
    private String to = ""; // 收件人地址
    private String subject = ""; // 邮件标题
    private String content = ""; //邮件内容
    private String port = "";
    private String transport = "";

    public MailUtils(String host, String protocol, String from, String fromPassword, String to, String subject, String content,String port) {
        this.host = host;
        this.protocol = protocol;
        this.from = from;
        this.fromPassword = fromPassword;
        this.to = to;
        this.subject = subject;
        this.content = content;
        this.port = port;
    }

    public void send() {
        try {
            Properties prop = new Properties();
            prop.setProperty("mail.host", host); //// 设置QQ邮件服务器
            prop.setProperty("mail.smtp.port",port);
            prop.setProperty("mail.transport.protocol", protocol); // 邮件发送协议
            prop.setProperty("mail.smtp.auth", "true"); // 需要验证用户名密码
            // 设置SSL加密
            MailSSLSocketFactory sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
            prop.put("mail.smtp.ssl.enable", "true");
            prop.put("mail.smtp.ssl.socketFactory", sf);
            //创建定义整个应用程序所需的环境信息的 Session 对象
            Session session = Session.getDefaultInstance(prop, new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    //发件人邮件用户名、授权码
                    return new PasswordAuthentication(from, fromPassword);
                }
            });
            //开启Session的debug模式，这样就可以查看到程序发送Email的运行状态
            session.setDebug(true);
            //2、通过session得到transport对象
            Transport ts = session.getTransport();
            //3、使用邮箱的用户名和授权码连上邮件服务器
            ts.connect(host, from, fromPassword);
            //创建邮件对象
            MimeMessage message = new MimeMessage(session);
            //指明邮件的发件人
            message.setFrom(new InternetAddress(from));
            //指明邮件的收件人，现在发件人和收件人是一样的，那就是自己给自己发
            message.setRecipient(Message.RecipientType.TO, new InternetAddress(to));
            //邮件的标题
            message.setSubject(subject);
            //邮件的文本内容
            message.setContent(content, "text/html;charset=UTF-8");
            //5、发送邮件
            ts.sendMessage(message, message.getAllRecipients());
            ts.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}